import time
import redis
from flask import Flask, render_template, jsonify

app = Flask(__name__)
try:
    r = redis.StrictRedis(host="192.168.52.140", port=6379, db=0, decode_responses=True)
    #127.0.0.1
except:
    print("连接失败！")

PreviousOrder = 0
temp = 0
temp_list_price = []
temp_list_time = []


@app.route('/')
def hello_world():  # put application's code here
    return render_template("main.html")


@app.route("/time")
def get_time():
    time_str = time.strftime("%Y{}%m{}%d{} %X")
    return time_str.format("年", "月", "日")


@app.route('/zong')
def get_zong_data():
    TotalPrice = r.get("TotalPrice")
    OrderNum = r.get("OrderNum")
    CustomNum = r.zcard("CustomNum")
    return jsonify({"TotalPrice": TotalPrice, "OrderNum": OrderNum, "CustomNum": CustomNum})


@app.route('/speed')
def get_speed():
    global PreviousOrder
    OrderNum = r.get("OrderNum")
    speed = int(OrderNum) - PreviousOrder
    PreviousOrder = int(OrderNum)
    return ("当前订单处理速度：" + str(speed) + "条/秒")


@app.route('/ditu')
def get_ditu_data():
    res = []
    CMap = r.zrevrange('CMap', 0, -1, withscores=True)
    for i in CMap:
        res.append({"name": i[0], "value": i[1]})
    return jsonify({"CMap": res})


@app.route('/booktop')
def get_book_top():
    res1 = []
    res2 = []
    data = r.zrevrange('BookTop', 0, 10, withscores=True)
    l = len(data)
    i = 0
    while (l - 1):
        if (data[i][0] != " "):
            res1.append(data[i][0])
            res2.append(data[i][1])
            i = i + 1
            l = l - 1
        else:
            i = i + 1
    # print({"type_list":type_list,"value_list":value_list})
    return jsonify({"na": res1, "value": res2})


@app.route('/presstop')
def get_press_top():
    res1 = []
    res2 = []
    data = r.zrevrange('PressTop', 0, 10, withscores=True)
    l = len(data)
    i = 0
    while (l - 1):
        if (data[i][0] != ""):
            res1.append(data[i][0])
            res2.append(data[i][1])
            i = i + 1
            l = l - 1
        else:
            i = i + 1
    # print({"type_list":type_list,"value_list":value_list})
    return jsonify({"na": res1, "value": res2})


@app.route('/payway')
def get_pwayway():
    res = []
    PayWay = r.zrevrange('PayWay', 0, -1, withscores=True)
    for i in PayWay:
        res.append({"value": i[1], "name": i[0]})
    return jsonify({"PayWay": res})


@app.route('/yunfei')
def get_yunfei():
    res1 = []
    res2 = []
    data = r.zrevrange('CMap', 0, 6, withscores=True)
    max = data[0][1]
    for i1, i2 in data:
        res1.append(i1)
        res2.append(round((i2 / max) * 50,2))
    # print({"type_list":type_list,"value_list":value_list})
    return jsonify({"site": res1, "value": res2})


if __name__ == '__main__':
    app.run()
